package com.hmkj.admin.controller.wx;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.HttpClientUtils;
import com.hmkj.common.utils.JsonUtils;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.wx.*;
import com.hmkj.core.po.wx.WxAccount;
import com.hmkj.core.po.wx.WxButton;
import com.hmkj.core.po.wx.WxClickReply;
import com.hmkj.core.service.wx.WxAccountService;
import com.hmkj.core.service.wx.WxButtonService;
import com.hmkj.core.service.wx.WxClickReplyService;
import com.hmkj.core.service.wx.impl.WeixinCore;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by SteveLi on 2016/7/19.
 */
@Log4j
@Controller
@RequestMapping(BaseController.BASE_URI)
public class WxButtonJsonController extends GenericController<Integer,WxButton> {
    @Resource
    WxButtonService wxButtonService;
    @Resource
    WxAccountService wxAccountService;
    @Resource
    WxClickReplyService wxClickReplyService;

    /**
     * 自定义菜单一级按钮列表JSON数据
     *
     * @param wxId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "wxmenu/json/list/{wxId}/{btnNum}", method = RequestMethod.GET)
    public ResultEntity menuListJson(@PathVariable Integer wxId, @PathVariable int btnNum) {
        ResultEntity resultEntity = new ResultEntity();
        HashMap<String, Object> map = new HashMap<String, Object>();
        resultEntity.setCode(ResultEntity.SUCCESS);
        List<WxButton> menuBtns = wxButtonService.select(new WxButton(t->t.setWxId(wxId)));
        if (btnNum == 1) {
            map.put("btninfo", menuBtns.get(0));
        }
        if (btnNum == 2) {
            map.put("btninfo", menuBtns.get(1));
        }
        if (btnNum == 3) {
            map.put("btninfo", menuBtns.get(2));
        }
        //调取点击事件列表
        List<WxClickReply> clickReplyList = wxClickReplyService.select(new WxClickReply(t->t.setDelFlag(GenericPo.DELFLAG.NORMAL.code)));
        map.put("clickReplyList", clickReplyList);
        resultEntity.setData(map);
        return resultEntity;
    }

    /**
     * 自定义菜单保存数据+上传给微信服务器
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "wxmenu/json/edit", method = RequestMethod.POST)
    public ResultEntity editMenu(Integer btnWxId, Integer btnId, String btnName, String btnType, String btnUrl, String btnClickReply) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode(ResultEntity.SUCCESS);
        resultEntity.setMessage("菜单同步成功！");
        try {
            //保存按钮数据
            WxButton btn = new WxButton();
            btn.setId(btnId);
            btn.setWxId(btnWxId);
            btn.setName(btnName);
            btn.setType(btnType);
            if (btnType.equals("view")) {
                btn.setData(btnUrl);
            } else if (btnType.equals("click")) {
                btn.setData(btnClickReply);
            } else {
                btn.setData(null);
            }
            wxButtonService.updateByPrimaryKeySelective(btn);
            //数据同步至微信服务器
            WeixinCore weixinCore = new WeixinCore();
            WxAccount wxaccount = wxAccountService.selectByPrimaryKey(btnWxId);
            String accesstoken = wxaccount.getAccesstoken();
            if (accesstoken == null) {
                accesstoken = weixinCore.getMpApiAccessToken(wxaccount.getAppid(), wxaccount.getAppsecret(), wxaccount.getId());
            }
            String weixinMenuCreateUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accesstoken;
            String menujson = getMenuInfoJson(btnWxId);
            log.error("菜单JSON:" + menujson);
            if (!menujson.equals("NoButton")) {
                URL url = new URL(weixinMenuCreateUrl);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                http.setRequestMethod("POST");
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
                System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
                http.connect();
                OutputStream os = http.getOutputStream();
                os.write(menujson.getBytes("UTF-8"));//传入参数
                os.flush();
                os.close();
                InputStream is = http.getInputStream();
                int size = is.available();
                byte[] jsonBytes = new byte[size];
                is.read(jsonBytes);
                String message = new String(jsonBytes, "UTF-8");
                HashMap<String, String> result = JsonUtils.toGenericObject(message, new TypeReference<HashMap<String, String>>() {
                });
                if (result.get("errcode").equals("0")) {
                    resultEntity.setCode(ResultEntity.SUCCESS);
                    resultEntity.setMessage("菜单同步成功！");
                } else {
                    log.error("weixin errcode:" + result.get("errcode"));
                    throw new Exception("同步失败");
                }
            } else {
                //删除自定义菜单
                String delResultJson = HttpClientUtils.httpGet("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accesstoken);
                HashMap<String, String> result = JsonUtils.toGenericObject(delResultJson, new TypeReference<HashMap<String, String>>() {
                });
                if (result.get("errcode").equals("0")) {
                    resultEntity.setCode(ResultEntity.SUCCESS);
                    resultEntity.setMessage("菜单同步成功！");
                } else {
                    log.error("weixin errcode:" + result.get("errcode"));
                    throw new Exception("同步失败");
                }
            }
        } catch (Exception ex) {
            log.error(ex.toString(), ex);
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage(ex.getMessage());
        }

        return resultEntity;
    }

    /**
     * 自定义菜单二级按钮列表JSON数据
     *
     * @param bid
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "submenu/json/list/{bid}", method = RequestMethod.GET)
    public ResultEntity subMenuListJson(@PathVariable Integer bid) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode(ResultEntity.SUCCESS);
        List<WxButton> subMenuBtns = wxButtonService.findSubMenuById(bid);
        resultEntity.setData(subMenuBtns);
        return resultEntity;
    }

    /**
     * 新增子菜单数据
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "submenu/json/save", method = RequestMethod.POST)
    public ResultEntity saveSubmenu(String btnList) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            WxButton[] subMenus = JsonUtils.toGenericObject(btnList, new TypeReference<WxButton[]>() {
            });
            wxButtonService.updateAll(subMenus);
            resultEntity.setCode(ResultEntity.SUCCESS);
            resultEntity.setMessage("更新数据成功");
        } catch (Exception ex) {
            log.error(ex.toString());
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage("保存失败");
        }
        return resultEntity;
    }

    /**
     * 编辑子菜单数据
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "submenu/json/edit", method = RequestMethod.POST)
    public ResultEntity editSubmenu(Integer btnWxId, Integer topBtnId, Integer btnId, String btnName, String btnType, String btnUrl, String btnClickReply) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            WxButton btn = new WxButton();
            btn.setId(btnId);
            btn.setWxId(btnWxId);
            btn.setTopBtn(topBtnId);
            btn.setName(btnName);
            btn.setType(btnType);
            if (btnType.equals("view")) {
                btn.setData(btnUrl);
            } else if (btnType.equals("click")) {
                btn.setData(btnClickReply);
            }
            wxButtonService.updateByPrimaryKeySelective(btn);
            resultEntity.setCode(ResultEntity.SUCCESS);
        } catch (Exception ex) {
            log.error(ex.toString());
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage("保存失败");
        }
        return resultEntity;
    }

    /**
     * 删除记录
     *
     * @param bid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submenu/json/del", method = RequestMethod.POST)
    public ResultEntity deleteSubmenu(@RequestParam(value = "bid") Integer bid) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            if (bid <= 0) {
                throw new BussinessException("参数错误");
            }
            wxButtonService.deleteByPrimaryKey(bid);
            resultEntity.setCode(ResultEntity.SUCCESS);
            resultEntity.setMessage("删除成功");
            return resultEntity;
        } catch (BussinessException e) {
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage("删除失败");
            return resultEntity;
        }
    }

    /**
     * 获取微信公众号自定义菜单描述json字符串
     *
     * @param wxId
     * @return String
     */
    public String getMenuInfoJson(int wxId) {
        List<WxButton> menuBtns = wxButtonService.select(new WxButton(t->t.setWxId(wxId)));
        List<WxButtonModel> buttons = new ArrayList<>();
        for (WxButton mainbtn : menuBtns) {
            if (mainbtn.getTopBtn() > 0 || mainbtn.getType() == null || mainbtn.getName() == null) {
                continue;
            }
            if (mainbtn.getType().equals("click")) {
                WxCommonClickButtonModel clickbtn = new WxCommonClickButtonModel();
                clickbtn.setType("click");
                clickbtn.setKey(mainbtn.getData());
                clickbtn.setName(mainbtn.getName());
                buttons.add(clickbtn);
            }
            if (mainbtn.getType().equals("view")) {
                WxCommonViewButtonModel viewbtn = new WxCommonViewButtonModel();
                viewbtn.setType("view");
                viewbtn.setUrl(mainbtn.getData());
                viewbtn.setName(mainbtn.getName());
                buttons.add(viewbtn);
            }
            if (mainbtn.getType().equals("subbtn")) {
                WxComplexButtonModel compbtn = new WxComplexButtonModel();
                compbtn.setName(mainbtn.getName());
                int wxbId = mainbtn.getId();
                List<WxButtonModel> sub_button = new ArrayList<>();
                for (WxButton btn : menuBtns) {
                    if (btn.getTopBtn() == wxbId && btn.getName() != null) {
                        if (btn.getType().equals("view")) {
                            WxCommonViewButtonModel viewbtn = new WxCommonViewButtonModel();
                            viewbtn.setType("view");
                            viewbtn.setUrl(btn.getData());
                            viewbtn.setName(btn.getName());
                            sub_button.add(viewbtn);
                        }
                        if (btn.getType().equals("click")) {
                            WxCommonClickButtonModel clickbtn = new WxCommonClickButtonModel();
                            clickbtn.setType("click");
                            clickbtn.setKey(btn.getData());
                            clickbtn.setName(btn.getName());
                            sub_button.add(clickbtn);
                        }
                    }
                }
                compbtn.setSub_button(sub_button);
                buttons.add(compbtn);
            }
        }
        if (buttons.size() == 0) {
            return "NoButton";
        }
        WxMenuModel menu = new WxMenuModel();
        menu.setButton(buttons);
        return JsonUtils.toJson(menu);
    }

    /**
     * 微信公众号自定义菜单同步更新至微信服务器
     *
     * @param wxId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "wxmenu/update/{wxId}", method = RequestMethod.GET)
    public ResultEntity menuUpdate(@PathVariable int wxId) {
        ResultEntity resultEntity = new ResultEntity();
        try {
            WeixinCore weixinCore = new WeixinCore();
            WxAccount wxaccount = wxAccountService.selectByPrimaryKey(wxId);
            String accesstoken = wxaccount.getAccesstoken();
            if (accesstoken == null) {
                accesstoken = weixinCore.getMpApiAccessToken(wxaccount.getAppid(), wxaccount.getAppsecret(), wxaccount.getId());
            }
            String weixinMenuCreateUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accesstoken;
            String menujson = getMenuInfoJson(wxId);
            log.error("菜单JSON:" + menujson);
            if (!menujson.equals("NoButton")) {
                URL url = new URL(weixinMenuCreateUrl);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                http.setRequestMethod("POST");
                http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
                System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
                http.connect();
                OutputStream os = http.getOutputStream();
                os.write(menujson.getBytes("UTF-8"));//传入参数
                os.flush();
                os.close();
                InputStream is = http.getInputStream();
                int size = is.available();
                byte[] jsonBytes = new byte[size];
                is.read(jsonBytes);
                String message = new String(jsonBytes, "UTF-8");
                HashMap<String, String> result = JsonUtils.toGenericObject(message, new TypeReference<HashMap<String, String>>() {
                });
                if (result.get("errcode").equals("0")) {
                    resultEntity.setCode(ResultEntity.SUCCESS);
                    resultEntity.setMessage("菜单同步成功！");
                } else {
                    log.error("weixin errcode:" + result.get("errcode"));
                    throw new Exception("同步失败");
                }
            } else {
                //删除自定义菜单
                String delResultJson = HttpClientUtils.httpGet("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accesstoken);
                HashMap<String, String> result = JsonUtils.toGenericObject(delResultJson, new TypeReference<HashMap<String, String>>() {
                });
                if (result.get("errcode").equals("0")) {
                    resultEntity.setCode(ResultEntity.SUCCESS);
                    resultEntity.setMessage("菜单同步成功！");
                } else {
                    log.error("weixin errcode:" + result.get("errcode"));
                    throw new Exception("同步失败");
                }
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage(ex.getMessage());
        }
        return resultEntity;
    }
}
